package cn.ztr.ymcc.web.controller;

import cn.ztr.ymcc.domain.Login;
import cn.ztr.ymcc.feign.UaaFeign;
import cn.ztr.ymcc.service.IEmployeeService;
import cn.ztr.ymcc.domain.Employee;
import cn.ztr.ymcc.query.EmployeeQuery;
import cn.ztr.ymcc.result.JsonResult;
import cn.ztr.ymcc.result.PageList;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Random;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private UaaFeign uaaFeign;

    @Autowired
    public IEmployeeService employeeService;

    /**
    * 保存和修改公用的
    */
    @PostMapping("/save")
    public JsonResult saveOrUpdate(@RequestBody @Valid Employee employee){
        if(employee.getId()!=null){
            employeeService.updateById(employee);
        }else{
            employeeService.save(employee);
            //创建login对象
            Login login = new Login();
            login.setPassword("123");
            login.setUsername(employee.getRealName());
            //添加到login表中
            JsonResult jsonResult = uaaFeign.saveOrUpdate(login);
            //获取添加的loginId
            String s = JSON.toJSON(jsonResult.getData()).toString();
            Login parse = JSON.parseObject(s,Login.class);
            //把loginId存入数据库
            employee.setLoginId(parse.getId());
            employeeService.updateById(employee);
        }
        return JsonResult.me();
    }

    /**
    * 删除对象
    */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        employeeService.removeById(id);
        return JsonResult.me();
    }

    /**
   * 获取对象
   */
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable("id")Long id){
        System.out.println(id);
        return JsonResult.me().setData(employeeService.getById(id));
    }

    /**
     * 根据loginId获取对象
     * @param id
     * @return
     */
    @GetMapping("/login/{id}")
    public JsonResult getByLoginId(@PathVariable("id")Long id){
        Employee employee = employeeService.getByLoginId(id);
        return JsonResult.me(employee);
    }


    /**
    * 查询所有对象
    */
    @GetMapping("/list")
    public JsonResult list(){
        Random random = new Random();
        int i = random.nextInt(10);
        i =1/0;
        return JsonResult.me().setData(employeeService.list(null));
    }


    /**
    * 带条件分页查询数据
    */
    @PostMapping("/pagelist")
    public JsonResult page(@RequestBody EmployeeQuery query){
        Page<Employee> page = new Page<Employee>(query.getPageNo(), query.getPageSize());
        page = employeeService.page(page);
        return JsonResult.me().setData(new PageList<Employee>(page.getTotal(), page.getRecords()));
    }
}
